package com.zhiwang.planet.mvvm.viewmodel.my

import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.zhiwang.planet.BR
import com.zhiwang.planet.R
import com.zhiwang.planet.di.ActivityScope
import com.zhiwang.planet.mvvm.model.RestApi
import com.zhiwang.planet.mvvm.model.request.FeedBackRequest2
import com.zhiwang.planet.util.Toaster
import com.zhiwang.planet.util.launchDelayError
import com.zhiwang.planet.util.suicideAfterTransition
import com.zhiwang.planet.util.withApiContext
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import me.tatarka.bindingcollectionadapter2.OnItemBind
import java.io.File
import javax.inject.Inject
import kotlin.collections.ArrayList

class SingleDataList<T> : ArrayList<T> {

    var data: T? = null
    var dataSize: Int

    constructor(data: T?, size: Int) : super() {
        this.data = data
        this.dataSize = size
    }


    override val size: Int
        get() = dataSize

    override fun get(index: Int): T {
        return data ?: throw IllegalStateException("not initialize data")
    }
}

//object AddImageEvent
//
//object DeleteImageEvent

object FeedBackVMConnection {


    var imgesToUpload = arrayListOf<File>()

    var title = MutableLiveData<String>()

    var content = MutableLiveData<String>()

    var onImageAddEvent = MutableLiveData<File>()

    var addImageEvent = MutableLiveData<Boolean>()

    var deleteImageEvent = MutableLiveData<File>()

    var previewImageEvent = MutableLiveData<File>()

    fun reset() {
        imgesToUpload = arrayListOf<File>()
        title = MutableLiveData<String>()
        onImageAddEvent = MutableLiveData<File>()
        addImageEvent = MutableLiveData<Boolean>()
        deleteImageEvent = MutableLiveData<File>()
        previewImageEvent = MutableLiveData<File>()
    }
}


class FeedBackImageItemViewModel(var file: File?) {

    private val MAX_ADVICE_IMAGE = 2

    val filePlaceHolderRes: Int
        get() = if (file == null) R.drawable.ic_add_image else 0

    fun add() {
        if (FeedBackVMConnection.imgesToUpload.size >= MAX_ADVICE_IMAGE) {
            Toaster.message("最多上传两张")
            return
        }
        if (file == null) {
            FeedBackVMConnection.addImageEvent.value = true
        } else FeedBackVMConnection.previewImageEvent.value = file
    }

    fun delete() {

        FeedBackVMConnection.deleteImageEvent.value = file

    }
}


class FeedBackItemViewModel(var advices: List<String>) {

    val TAG = "FeedBackItemViewModel"
    var images = MutableLiveData(arrayListOf(FeedBackImageItemViewModel(null)))


    init {

        FeedBackVMConnection.deleteImageEvent.observeForever { toDeleteFile ->
            val rest = images.value!!.filter { toDeleteFile != it.file } as ArrayList
            images.value = rest
            FeedBackVMConnection.imgesToUpload.remove(toDeleteFile)
        }

        FeedBackVMConnection.onImageAddEvent.observeForever {

            val newList: ArrayList<FeedBackImageItemViewModel> = arrayListOf()
            newList.add(FeedBackImageItemViewModel(it))
            newList.addAll(images.value ?: arrayListOf())
            images.value = newList
        }
    }

    var imagesBinding = OnItemBind<FeedBackImageItemViewModel?> { binding, position, model ->

            binding.set(BR.feedbackImageVm, R.layout.item_advice_upload_image)

    }

    var content = MutableLiveData<String>()

}

@ActivityScope
class FeedBackViewModel @Inject constructor(var activity: AppCompatActivity, var restApi: RestApi) : ViewModel() {


    var errHandler: ((Throwable) -> Unit)? = null

    val advicelist = arrayListOf<String>()

    val checkedTag = MutableLiveData<String>()

    val items = MutableLiveData<SingleDataList<FeedBackItemViewModel>>()

    lateinit var itemVm: FeedBackItemViewModel

    val itemBinding = OnItemBind<FeedBackItemViewModel> { binding, position, model ->

        when (position) {
            0 -> binding.set(BR.feedbackItemVm, R.layout.item_advice_header)
            1 -> binding.set(BR.feedBackVm1, R.layout.item_davice_typelist).bindExtra(BR.feedBackMainVm, this)
            2 -> binding.set(BR.feedbackItemVm2, R.layout.item_advice_content)
            3 -> binding.set(BR.feedbackItemVm3, R.layout.item_imagelist).bindExtra(BR.feedBackMainVm, this)
        }
    }

    fun loadAdviceList() {

        viewModelScope.launchDelayError(errHandler = errHandler) {
            val list = withApiContext { restApi.loadAdviceTypeList() }

            advicelist.clear()
            advicelist.addAll(list)
            items.value = SingleDataList(FeedBackItemViewModel(list).also { itemVm = it }, 4)
        }

    }

    val TAG = "FeedBackViewModel"

    fun submit() {

        viewModelScope.launchDelayError(errHandler = errHandler) {

            if (checkedTag.value == null) {
                Toaster.message("请先选择问题类型")
                return@launchDelayError
            }
            val title = checkedTag.value ?: "APP不稳定"
            val feeBack = FeedBackRequest2.create(title, itemVm.content.value
                    ?: "----🗻🍁🍜用户未提交内容😍🐷🐶----", FeedBackVMConnection.imgesToUpload)

            val res = withContext(Dispatchers.IO) { restApi.sendFeedBack2(feeBack) }

            if (res.isOk()){
                FeedBackVMConnection.reset()
                Toaster.message("提交反馈成功")
                activity.suicideAfterTransition()
            }else Toaster.message(res.errMsg)
        }
    }


}